package com.harmontronics.app.pedestal.bridge;

import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.harmontronics.app.pedestal.R;
import com.harmontronics.app.pedestal.bridge.model.BaseBridge;
import com.harmontronics.app.pedestal.bridge.model.BridgeChooseResult;
import com.harmontronics.app.pedestal.bridge.model.BridgeFile;
import com.harmontronics.app.pedestal.picture.GlideEngine;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import wendu.dsbridge.CompletionHandler;

public class ImageBridge extends BaseBridge {

    @JavascriptInterface
    public void choose(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("IMAGE.choose");
        if (null == argsJson) {
            handler.complete(fail("参数不能为空", null));
            return;
        }

        try {
            OnResultCallbackListener<LocalMedia> callback = new OnResultCallbackListener<LocalMedia>() {
                @Override
                public void onResult(List<LocalMedia> result) {
                    // LocalMedia Returns Five Paths
                    // 1.media.getPath();
                    // 2.media.getCutPath();
                    // 3.media.getCompressPath();
                    // 4.media.getOriginalPath());
                    // 5.media.getAndroidQToPath();
                    List<String> tempFilePaths = new ArrayList<>();
                    List<BridgeFile> tempFiles = new ArrayList<>();
                    for (LocalMedia media : result) {
                        tempFilePaths.add(media.getRealPath());
                        BridgeFile file = new BridgeFile(media.getSize(), media.getRealPath());
                        tempFiles.add(file);
                    }
                    BridgeChooseResult chooseResult = new BridgeChooseResult(tempFilePaths, tempFiles);
                    LogUtils.d("chooseResult: " + chooseResult.toJson());
                    handler.complete(success(chooseResult));
                }

                @Override
                public void onCancel() {
                    handler.complete(fail("cancel", null));
                }
            };

            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
//            count: 6, //默认9
//            extension: ["png"],
//            sourceType: ["album"], //从相册选择

//            MIME_TYPE_PNG = "image/png";
//            MIME_TYPE_JPEG = "image/jpeg";
//            MIME_TYPE_JPG = "image/jpg";
//            MIME_TYPE_BMP = "image/bmp";
//            MIME_TYPE_GIF = "image/gif";
//            MIME_TYPE_WEBP = "image/webp";
            String[] extensions = null;
            if (args.has("extension")) {
                JSONArray extension = args.getJSONArray("extension");
                if (extension.length() > 0) {
                    extensions = new String[extension.length()];
                    for (int i = 0; i < extension.length(); i++) {
                        String ext = extension.getString(i);
                        switch (ext.toUpperCase()) {
                            case "PNG":
                                extensions[i] = PictureMimeType.ofPNG();
                                break;
                            case "JPG":
                            case "JPEG":
                                extensions[i] = PictureMimeType.ofJPEG();
                                break;
                            case "WEBP":
                                extensions[i] = PictureMimeType.ofWEBP();
                                break;
                            case "BMP":
                                extensions[i] = PictureMimeType.ofBMP();
                                break;
                            case "GIF":
                                extensions[i] = PictureMimeType.ofGIF();
                                break;
                            default:
                                break;
                        }
                    }
                }
            }

            boolean useCamera = true;
            boolean useGallery = true;

            if (args.has("sourceType")) {
                JSONArray sourceType = args.getJSONArray("sourceType");
                List<String> sourceTypes = new ArrayList<>();
                if (sourceType.length() > 0) {
                    for (int i = 0; i < sourceType.length(); i++) {
                        sourceTypes.add(sourceType.getString(i));
                    }
                    useCamera = sourceTypes.contains("camera");
                    useGallery = sourceTypes.contains("album");
                }
            }

            boolean useAll = useCamera && useGallery;

            if (useAll) {
                PictureSelector.create(ActivityUtils.getTopActivity())
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideEngine.createGlideEngine())
                        .isUseCustomCamera(true)
                        .setOutputCameraPath(createCustomCameraOutPath(true))
                        .maxSelectNum(args.has("count") ? args.getInt("count") : 9)
                        .queryMimeTypeConditions(extensions)
                        .forResult(callback);
            } else {
                if (useCamera) {
                    PictureSelector.create(ActivityUtils.getTopActivity())
                            .openCamera(PictureMimeType.ofImage())
                            .imageEngine(GlideEngine.createGlideEngine())
                            .isUseCustomCamera(true)
                            .setOutputCameraPath(createCustomCameraOutPath(true))
                            .maxSelectNum(args.has("count") ? args.getInt("count") : 9)
                            .queryMimeTypeConditions(extensions)
                            .forResult(callback);

                }

                if (useGallery) {
                    PictureSelector.create(ActivityUtils.getTopActivity())
                            .openGallery(PictureMimeType.ofImage())
                            .isCamera(false)
                            .imageEngine(GlideEngine.createGlideEngine())
                            .maxSelectNum(args.has("count") ? args.getInt("count") : 9)
                            .queryMimeTypeConditions(extensions)
                            .forResult(callback);
                }

                handler.complete(fail("choose fail", null));
            }
        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }
    }

    @JavascriptInterface
    public void preview(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("IMAGE.preview");
        if (null == argsJson) {
            handler.complete(fail("参数不能为空", null));
            return;
        }

        try {
            JSONObject args = (JSONObject) argsJson;
            LogUtils.d("args: " + args.toString());
            List<LocalMedia> paths = new ArrayList<>();
            if (args.has("paths")) {
                JSONArray pathArray = args.getJSONArray("paths");
                if (pathArray.length() > 0) {
                    for (int i = 0; i < pathArray.length(); i++) {
                        LocalMedia path = new LocalMedia();
                        path.setPath(pathArray.get(i).toString());
                        paths.add(path);
                    }
                }
            }
            PictureSelector.create(ActivityUtils.getTopActivity())
                    .themeStyle(R.style.picture_default_style)
                    .isNotPreviewDownload(args.has("download") ? args.getBoolean("download") : true)
                    .imageEngine(GlideEngine.createGlideEngine())
                    .openExternalPreview(args.has("current") ? args.getInt("current") : 0, paths);
            handler.complete(success("preview success"));
        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }
    }
}
